<template>
  <div class="warpper-box">
    <form-create v-model="params.fApi" :rule="params.rule" :option="params.option" @btn-search-click="loadTable(true)"
      @btn-reset-click="reset" @btn-add-click="add(true)" />
    <a-button type="danger" v-action:roleAddBtn @click="add(true)" icon="plus">新增</a-button>
    <a-table :columns="table.columns" :pagination="table.pagination" @change="handleTableChange" rowKey="id"
      :data-source="table.loadData">
      <span slot="action" slot-scope="text, record">
        <a v-action:roleEditBtn @click="add(record)">编辑</a>
        <a-divider v-action:roleEditBtn type="vertical" />
        <a-popconfirm title="是否删除?" ok-text="删除" cancel-text="取消" @confirm="del(record)">
          <a v-action:roleDelBtn href="#">删除</a>
        </a-popconfirm>
        <a-divider v-action:roleDelBtn type="vertical" />
        <a v-action:rolePermissionBtn @click="$refs.createTree.add(record, 'typeMenuId', 'roleId')">权限配置</a>
        <a-divider v-action:roleFieldBtn type="vertical" />
        <a v-action:roleFieldBtn @click="setField(record)">字段配置</a>
        <a-divider v-action:roleDataPermissionBtn type="vertical" />
        <a v-action:roleDataPermissionBtn @click="setDataField(record)">数据权限</a>

      </span>
    </a-table>
    <a-modal :title="title" :width="640" :visible="visible" @ok="handleSubmit" @cancel="visible = false">
      <form-create v-model="form.fApi" :rule="form.rule" :option="form.option" />
    </a-modal>
    <a-modal title="设置数据权限" :width="640" :visible="fieldVisible" :confirmLoading="field.loading" @ok="handlefieldSubmit"
      @cancel="fieldVisible = false">
      <form-create v-model="field.fApi" :rule="field.rule" :option="field.option" />
    </a-modal>
    <create-tree ref="createTree" @ok="treeSubmit" />
  </div>
</template>

<script>
import store from '@/store'
import { mapGetters } from 'vuex'
import {
  getSysRoleList,
  addSysRole,
  editSysRole,
  getSysDelRole,
  setRoleDataPermission,
  getRoleDataPermission
} from '@/api/manage/role'
import CreateTree from './modules/createTree'
import {
  PARAMS_ROLE,
  FORM_ROLE,
  FORM_FIELD_ROLE,
  FORM_ENTERPRISE_ROLE,
  ROLE_COLUMNS,
  ROLE_ENTERPRISE_COLUMNS,
  OPTION_BLOCK,
  OPTION_INLINE
} from './modules/form'
export default {
  name: 'role',
  components: {
    CreateTree
  },
  data() {
    return {
      params: {
        fApi: {},
        rule: PARAMS_ROLE,
        option: OPTION_INLINE
      },
      form: {
        fApi: {},
        rule: [],
        option: OPTION_BLOCK
      },
      field: {
        id: '',
        loading: false,
        fApi: {},
        rule: [],
        option: OPTION_BLOCK
      },
      visible: false,
      title: '',
      fieldVisible: false,
      table: {
        columns: ROLE_COLUMNS,
        loadData: [],
        pagination: {
          total: 0,
          current: 1,
          pageSize: 10,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      userTypeOptions: []
    }
  },
  mounted() {
    this.ininColumus();
    this.ininUserTypeData();
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    async ininUserTypeData() {
      this.userTypeOptions = await store.dispatch('sysGetUserTypeData');
    },
    ininColumus() {
      this.table.columns = this.userInfo.type === 1 ? ROLE_COLUMNS : ROLE_ENTERPRISE_COLUMNS;
      this.loadTable(true);
    },
    async loadTable(flag) {
      let params = {};
      if (JSON.stringify(this.params.fApi) !== "{}") {
        params.roleName = this.params.fApi.getValue('roleName');
      }
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.roleRelationId = this.userInfo.relationId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await getSysRoleList(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    add(rows) {
      let that = this;
      this.form.rule = FORM_ROLE;
      let setUserType = this.userInfo.availableType ? this.userInfo.availableType.split(',') : [];
      let setUserTypeData = [];
      this.userTypeOptions.forEach(v => {
        if (setUserType.includes(v.value)) {
          setUserTypeData.push(v);
        }
      })
      this.$nextTick(() => {
        this.form.fApi.updateRules({ 'roleTypeCode': { options: setUserTypeData }, 'availableType': { options: setUserTypeData } })//,'availableType':{options:this.userInfo.availableType}
      });
      if (rows === true) {
        this.id = '';
        this.title = "新增";
        this.$nextTick(() => {
          this.form.fApi.setValue({
            roleName: '',
            roleTypeCode: '',
            availableType: [],
            roleDescription: ''
          })
        })
      } else {
        this.id = rows.id;
        this.title = "编辑";
        this.$nextTick(() => {
          this.form.fApi.setValue({
            roleName: rows.roleName,
            roleTypeCode: rows.roleTypeCode,
            roleDescription: rows.roleDescription,
            availableType: rows.availableType ? rows.availableType.split(',') : []
          })
        })
      }
      this.visible = true;
    },
    handleSubmit() {
      this.form.fApi.submit(async (formData, $f) => {
        try {
          if (this.id) {
            formData.id = this.id;
          }
          formData.availableType = formData.availableType.join(',');
          const { code } = this.id ? await editSysRole(formData) : await addSysRole(formData);
          if (code === '1') {
            this.visible = false;
            this.loadTable(true);
          }
        } catch (error) {
          this.$message.info(JSON.stringify(error));
        }
      })
    },
    treeSubmit() {
      this.loadTable(false);
    },
    async del(row) {
      let params = {
        id: row.id
      }
      const { code } = await getSysDelRole(params);
      if (code === '1') {
        this.$message.success('操作成功');
        this.loadTable(false);
      }
    },
    setField(rows) {
      this.$router.push({ name: 'permissionFieldCode', query: { roleId: rows.roleId, flag: 'permissionRoleCode', roleName: rows.roleName } });
    },
    async setDataField(rows) {
      this.field.rule = FORM_FIELD_ROLE;
      this.field.id = rows.roleId;
      const { code, data } = await getRoleDataPermission(rows.roleId);
      if (code == '1') {
        this.fieldVisible = true;
        if (data) {
          this.$nextTick(() => {
            this.field.fApi.resetFields();
            this.field.fApi.getRule('customInfo').title = '';
            this.field.fApi.getRule('type').value = data.type;
            this.field.fApi.on('btn-radio-change', this.radioChange);
          })
          this.radioChange(data.type);
        } else {
          this.$nextTick(() => {
            this.field.fApi.resetFields();
            this.field.fApi.getRule('customInfo').title = '';
            this.field.fApi.on('btn-radio-change', this.radioChange);
          })
        }
      }

    },
    radioChange(e) {
      let value = 0;
      if (e.target) {
        value = e.target.value;
      } else {
        value = e;
      }
      this.$nextTick(() => {
        const rule = this.field.fApi.getRule('customInfo');
        const type = this.field.fApi.getRule('type');
        const _rule = type.options.find(v => v.value == value);
        rule.title = _rule.content;
      })
    },
    handlefieldSubmit() {
      this.field.fApi.submit(async (formData, $f) => {
        try {
          formData.roleId = this.field.id;
          this.field.loading = true;
          const { code } = await setRoleDataPermission(formData);
          this.field.loading = false;
          if (code === '1') {
            this.$message.success('分配成功');
            this.fieldVisible = false;
            this.loadTable(true);
          }
        } catch (error) {
          that.$warning({
            title: '网络不稳定，重试或者联系管理员',
            okText: '关闭'
          });
        }
      })
    },
    reset() {
      this.params.fApi.resetFields();
      this.loadTable(true);
    }
  }
}
</script>


